package cn.fyl.user.service.impl;

import cn.fyl.basic.constant.RegisterConstant;
import cn.fyl.basic.exception.BusinessException;
import cn.fyl.basic.jwt.JwtUtils;
import cn.fyl.basic.jwt.RsaUtils;
import cn.fyl.basic.util.HttpUtil;
import cn.fyl.basic.util.JsonResult;
import cn.fyl.basic.util.Md5Utils;
import cn.fyl.basic.util.StrUtils;
import cn.fyl.org.mapper.EmployeeMapper;
import cn.fyl.system.domain.Menu;
import cn.fyl.user.constant.WxConstants;
import cn.fyl.user.domain.LoginInfo;
import cn.fyl.user.domain.User;
import cn.fyl.user.domain.WxUser;
import cn.fyl.user.dto.LoginData;
import cn.fyl.user.dto.LoginDto;
import cn.fyl.user.dto.WxDto;
import cn.fyl.user.mapper.LoginInfoMapper;
import cn.fyl.user.mapper.UserMapper;
import cn.fyl.user.mapper.WxUserMapper;
import cn.fyl.user.service.ILoginService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 账号密码登陆
     * @param dto
     * @return
     */

    @Override
    public Map<String, Object> account(LoginDto dto) {
        //根据手机号和type查询logininfo
        LoginInfo loginInfo = loginInfoMapper.getLogininfoByDto(dto);
        if(loginInfo==null){
            throw new BusinessException("账号不存在！");
        }
        // 判断密码是否正确，加盐加密
        String byMd5 = Md5Utils.encrypByMd5(loginInfo.getSalt() + dto.getPassword());
        if(!byMd5.equals(loginInfo.getPassword())){
            throw new BusinessException("密码不正确！");
        }
        // 将数据保存到redis中，设置过期时间
       /* String token = UUID.randomUUID().toString();//随机生成一个uuid保证唯一
        redisTemplate.opsForValue().set(token,loginInfo,30, TimeUnit.MINUTES);//设置时间为三十分钟过期

        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        loginInfo.setSalt(null);
        loginInfo.setPassword(null);
        map.put("loginInfo",loginInfo);*/
        Map<String,Object> map = loginSuccessJwtHandler(loginInfo);

        return map;
    }

    @Override
    public JsonResult weChat(String code) {
        /**
         * 1.校验之前是否绑定过
         *  1.1 先根据code获取token，openID
         *  1.2根绝openID查询
         *      如果存在，之前绑定过，直接免密登陆
         *      如果不存在，之前没有绑定过，跳转到绑定页面，进行绑定
         *
         */
        // 发送第二次请求，获取token和openID
        String jsonStr = HttpUtil.httpGet(WxConstants.GET_ACK_URL
                .replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", code)
        );
        // 将json字符串转成json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        WxUser dbWxUser = wxUserMapper.loadByOpenId(openid);
        if (dbWxUser!=null&&dbWxUser.getUser_id()!=null){
            // 获取logininfo信息。
            LoginInfo loginInfo = loginInfoMapper.loadByUserId(dbWxUser.getUser_id());

            // 随机生成一个key（token）
           /* String token = UUID.randomUUID().toString();
            // 设置三十分钟过去
            redisTemplate.opsForValue().set(token,loginInfo,30, TimeUnit.MINUTES);

            // 准备一个map
            HashMap<String, Object> map = new HashMap<>();

            map.put("token",token);
            // 把盐值，和密码设置为null
            loginInfo.setSalt(null);
            loginInfo.setPassword(null);
            map.put("loginInfo",loginInfo);*/
            Map<String,Object> map = loginSuccessJwtHandler(loginInfo);

            // controller
            return JsonResult.me().setResultObj(map);


        }else {
            // 第一次扫码，将access_token和openid返回给前端
            String param = "?accessToken="+access_token+"&openId="+openid;
            return JsonResult.me().setMsg("绑定").setResultObj(param);
        }

    }

    @Override
    public JsonResult binder(WxDto dto) {
        String accessToken = dto.getAccessToken();
        String openId = dto.getOpenId();
        String phone = dto.getPhone();
        String verifyCode = dto.getVerifyCode();
        // 校验
        if(StringUtils.isEmpty(phone)
                ||StringUtils.isEmpty(verifyCode)
                ||StringUtils.isEmpty(accessToken)
                ||StringUtils.isEmpty(openId)){
            throw  new BusinessException("参数不能为空");
        }
        // 校验验证码
        Object obj = redisTemplate.opsForValue().get(phone + RegisterConstant.WXBINDER);
        if(obj==null){
            throw  new BusinessException("验证码过期，请重新获取！");
        }
        if(!verifyCode.equalsIgnoreCase(obj.toString().split(":")[0])){
            throw  new BusinessException("验证码输入错误，请重新输入！");
        }

        // 发送第三次请求，获取wxuser https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
        String jsonObj = HttpUtil.httpGet(WxConstants.GET_USER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId)
        );

        WxUser wxUser = jsonObj2WxUser(jsonObj);

        // 通过手机号查询user，如果查到，直接绑定
        User dbuser = userMapper.findByPhone(phone);
        if(dbuser==null){
            //没有绑定过，生成一个user对象
            dbuser = phone2User(phone);
            LoginInfo dbloginInfo = user2Logininfo(dbuser);
            // 保存打LoginInfo，返回主键自增
            loginInfoMapper.save(dbloginInfo);

            // 携带LoginInfoid保存到user中
            dbuser.setLogininfo_id(dbloginInfo.getId());
            userMapper.save(dbuser);
        }
        // 将user的id赋值给wxuser，绑定
        wxUser.setUser_id(dbuser.getId());
        wxUserMapper.save(wxUser);
        // 通过user的LoginInfoid查询LoginInfo
        LoginInfo loginInfo = loginInfoMapper.loadById(dbuser.getLogininfo_id());
        // 免密登录。
       /* String token = UUID.randomUUID().toString();
        // 设置三十分钟过去
        redisTemplate.opsForValue().set(token,loginInfo,30, TimeUnit.MINUTES);

        // 准备一个map
        HashMap<String, Object> map = new HashMap<>();

        map.put("token",token);
        // 把盐值，和密码设置为null
        loginInfo.setSalt(null);
        loginInfo.setPassword(null);
        map.put("loginInfo",loginInfo);*/
        Map<String,Object> map = loginSuccessJwtHandler(loginInfo);

        // controller
        return JsonResult.me().setResultObj(map);

    }

    private LoginInfo user2Logininfo(User dbuser) {
        LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(dbuser,loginInfo);
        return loginInfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        // 生成一个颜值， 密码
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);

        // 生一个密码
        String password = StrUtils.getComplexRandomString(6);

        // 加密
        String dbPassword = Md5Utils.encrypByMd5(salt + password);
        user.setPassword(dbPassword);

        return user;

    }

    private WxUser jsonObj2WxUser(String jsonObj) {
        // 把jsonobj转成json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonObj);

        WxUser wxUser = new WxUser();
        wxUser.setAddress(jsonObject.getString("country"));
        wxUser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxUser.setNickname(jsonObject.getString("nickname")); // 昵称
        wxUser.setOpenid(jsonObject.getString("openid"));
        wxUser.setSex(jsonObject.getInteger("sex"));
        wxUser.setUnionid(jsonObject.getString("unionid"));

        return wxUser;

    }

    private Map<String, Object> loginSuccessJwtHandler(LoginInfo loginInfo) {
        //创建LoginData对象用于等会通过私钥加密
        LoginData loginData = new LoginData();
        loginData.setLoginInfo(loginInfo);
        Map<String, Object> map = new HashMap<>();
        try {
            //1.获取loginInfo
            if(loginInfo.getType()==0){//管理员
                //2.获取当前登陆人的所有权限 - sn
                List<String> permissions = employeeMapper.loadPermissionsByLogininfoId(loginInfo.getId());
                //3.获取当前登陆人的所有菜单 - 【难度】
                List<Menu> menus = employeeMapper.loadMenusByLogininfoId(loginInfo.getId());
                loginData.setPermissions(permissions);
                loginData.setMenus(menus);
                //将当前登陆人的权限和菜单添加到map - 响应给前端
                map.put("permissions",permissions);
                map.put("menus",menus);
            }
            //4.通过私钥对登录信息进行加密 - jwtToken串
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader()                                             	  .getResource("auth_rsa.pri").getFile());
            //将登陆人信息加密得到jwtToken串
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30000000);
            //5.装到map返回
            map.put("token",jwtToken);
            map.put("loginInfo",loginInfo);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
